package com.eagle.view.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.eagle.R;
import com.eagle.support.constants.Constants;
import com.eagle.view.activity.base.BaseCallActivity;
import com.eagle.view.fragment.call.FragmentCall;
import com.eagle.view.fragment.call.FragmentCallOperation;
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog;
import com.kinstalk.voip.sdk.EngineSdkCallState;
import com.kinstalk.voip.sdk.EngineSdkVideoPixelFormat;
import com.kinstalk.voip.sdk.logic.sip.aidl.model.CallInfo;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentById;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.ViewById;

/**
 * Created by gc on 2017/1/11. 视屏通话页面
 */
@EActivity(R.layout.activity_video_call)
public class VideoCallActivity extends BaseCallActivity {

    @FragmentById(R.id.fragment_call)
    protected FragmentCall mFragmentCall;

    @FragmentById(R.id.fragment_call_operation)
    protected FragmentCallOperation mFragmentCallOperation;

    @ViewById(R.id.layout_parent)
    protected RelativeLayout mLayoutParent;

    @Extra(Constants.CALL_TYPE_CALL_ANSWER)
    protected boolean mFromCallAnswer;

    private boolean mHangup = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initExplodeTransition();
    }

    @AfterViews
    void initView() {
        handlerFullscreen(mFromCallAnswer);
    }

    private void handlerFullscreen(boolean fullscreen) {
        if (fullscreen) {
            getSupportFragmentManager().beginTransaction().show(mFragmentCall).hide(mFragmentCallOperation).commitAllowingStateLoss();
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            mLayoutParent.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(params);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        } else {
            getSupportFragmentManager().beginTransaction().show(mFragmentCallOperation).hide(mFragmentCall).commitAllowingStateLoss();
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            setDarkStatusIcon(true);
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(params);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        }
    }

    @Override
    public void onCallStateHandler(CallInfo call, int state) {
        super.onCallStateHandler(call, state);
        switch (EngineSdkCallState.swigToEnum(state)) {
            case ES_STATE_ON_CALL_CALL_ENDED:
                //对方挂断
                if (!mHangup) {
                    new MaterialStyledDialog.Builder(this)
                            .setHeaderColorInt(R.color.gray_transparent)
                            .setDescription("The other party has hung up the phone.")
                            .setPositiveText("OK")
                            .setCancelable(false)
                            .onPositive((dialog, which) -> {
                                mFragmentCall.handlerFinish();
                                finishPage();
                            })
                            .show();
                } else {
                    dismissLoading();
                    mFragmentCall.handlerFinish();
                    finishPage();
                }
                break;
            case ES_STATE_ON_CALL_IN_ACTIVE_SESSION:
                if (!mFromCallAnswer) {
                    handlerFullscreen(true);
                }
                break;
        }
    }

    @Override
    public void onMainVideoDataInCall(long callToken, long pointer, int width, int height, char rotation, EngineSdkVideoPixelFormat format, long channelId) {
        super.onMainVideoDataInCall(callToken, pointer, width, height, rotation, format, channelId);
        if (!mFragmentCall.isHidden())
            mFragmentCall.onMainVideoDataInCall(pointer, width, height, rotation);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isLoading()) {
                dismissLoading();
                return true;
            }

            if (!mFragmentCall.isHidden()) {
                popQuitLiveDialog();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Receiver(actions = Constants.OUT_CALL_ANSWERED, registerAt = Receiver.RegisterAt.OnCreateOnDestroy)
    protected void onAnswer() {
        handlerFullscreen(true);
    }

    /**
     * 弹出退出通话
     */
    public void popQuitLiveDialog() {
        new MaterialStyledDialog.Builder(this)
                .setHeaderColorInt(R.color.gray_transparent)
                .setDescription("Whether to hang up the phone?")
                .setPositiveText("OK")
                .setNegativeText("CANCEL")
                .setCancelable(true)
                .autoDismiss(true)
                .onPositive((dialog, which) -> {
                    mHangup = true;
                    showLoading();
                    new Handler().postDelayed(() -> mCallHelper.hangUpCall(), 500);
                })
                .show();
    }

    /**
     * 流量监听
     */
    protected void receiverSpeed(String rx, String tx) {
        if (!mFragmentCall.isHidden()) mFragmentCall.receiverSpeed(rx, tx);
    }
}
